package FileHandling;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import Entities.Entity;
import InstanceHandling.Dungeon;
import InstanceHandling.Instance;


public class XMLFileReader extends DefaultHandler {

	public List<Entity> tempList;
	String xmlFile;
	Entity tempBoss;
	String instanceName;
	String tmpValue;
	Instance tempInstance;
	
	public XMLFileReader(String xmlFile) {
		this.xmlFile = xmlFile;
		tempList = new ArrayList<Entity>();
		parseXML();
	}

	private void parseXML() {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser parser = factory.newSAXParser();
			parser.parse(xmlFile, this);
		} catch (ParserConfigurationException e) {
			System.out.println("Parse config error");
		} catch (SAXException e) {
			System.out.println("SAX Exception: xml not well formed!");
		} catch (IOException e) {
			System.out.println("IO Error");
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		tmpValue = new String(ch, start, length);	
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equalsIgnoreCase("instance")) {
			tempList.clear();
			tempInstance = new Instance();
			tempInstance.setName(attributes.getValue("id"));
		}
		
		if (qName.equalsIgnoreCase("boss")) {
			tempBoss = new Entity();
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		//every boss should be added to the importList
		if (qName.equalsIgnoreCase("boss")) {
			tempInstance.getBossmobs().add(tempBoss);
		}
		if (qName.equalsIgnoreCase("name")) {
			tempBoss.setName(tmpValue);
		}
		if (qName.equalsIgnoreCase("instance")) {
			Dungeon.instances.add(tempInstance);
		}
	}
}
